﻿Ext.require([
    'Twi.Msg',
    'Twi.Tbar',
    'Twi.QuickAjax',
    'Twi.QuickGrid',
    'Twi.QuickWin',
    'BIM.store.TreeMapping',
    //'BIM.store.Tree',
    'TAB.view.tree.TreeNewOrEditForm'
]);

Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    twiSelf.init();
});

Twi.TAB.TreeManage = {
    Vars: {
        treeMappingGrid: null,
        treePanel: null,
        treeMappingName: 'SM002',
        sltTreeMappingValue: null
    } //end Vars

    , init: function () {
        twiVars.treeMappingGrid = twiSelf.Grid.createTreeMappingGrid();
        twiVars.treePanel = twiSelf.Tree.createTreePanel2();
    } //end init

    , Grid: {
        createTreeMappingGrid: function () {
            var store = Ext.create('BIM.store.TreeMapping');
            var grid = Ext.create("Twi.QuickGrid", {
                title: '树结构类别',
                //forceFit:true,
                store: store,
                renderTo: 'treeMappingGrid',
                columns: [{ xtype: 'rownumberer', width: 30 },
                 {
                     header: '名称',
                     dataIndex: 'FTEXT',
                     flex: 2
                 }, {
                     header: '排序',
                     dataIndex: 'FSORT',
                     flex: 1
                 }]
            });
            grid.on('itemclick', function (view, record) {
                twiVars.sltTreeMappingValue = record.data.FVALUE;
                Twi.QuickAjax.Ajax({
                    params: {
                        cn: 'Tree',
                        mn: 'TAB',
                        mn2: 'GetTreeData',
                        value: record.data.FVALUE
                    },
                    success: function (twi) {
                        var tree = twiVars.treePanel;
                        tree.store.setRootNode(twi.data[0]);
                        //tree.expandAll();
                        tree.expandNode(tree.getRootNode());
                    }
                });

                //twiVars.treePanel.store.proxy.extraParams.value = record.data.FVALUE;
                //twiVars.treePanel.store.load();
            });
            return grid;
        } //end createTreeMappingGrid

    } //end Grid

    , Tree:
    {
        //这个是异步加载每个节点的方式（体验不是很好）
        createTreePanel: function () {
            var store = Ext.create('BIM.store.Tree');
            var actionItems = twiSelf.ActionItems.createTreeItems();
            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: actionItems
            });
            var tree = Ext.create('Ext.tree.Panel', {
                title: '树结构详细',
                store: store,
                rootVisible: false,
                height: $(document).height() - Twi.TokenHeight - 3, //自适应高度 
                autoScroll: true,
                useArrows: true,
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'top',
                    items: actionItems
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function (view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },
                renderTo: 'treeGrid'
            });
            //tree.expandAll();
            return tree;

        } //end  createTreePanel

        //这个方式是直接加载整棵树
        , createTreePanel2: function () {
            var store = Ext.create('Ext.data.TreeStore', {
                fields: ['text', 'level', 'children', 'leaf', 'id', 'parentid', 'code', 'dict']
            });
            var actionItems = twiSelf.ActionItems.createTreeItems();
            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: actionItems
            });
            var tree = Ext.create('Ext.tree.Panel', {
                title: '树结构详细',
                store: store,
                rootVisible: true,
                height: $(document).height() - Twi.TokenHeight - 3, //自适应高度 
                autoScroll: true,
                useArrows: true,
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'top',
                    items: actionItems
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function (view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },
                renderTo: 'treeGrid'
            });

            return tree;
        } //end createTreePanel2



    }//end Tree


    , ActionItems: {

        createTreeItems: function () {
            var items = Twi.Tbar.CRUD(twiSelf.Fn.Tree.btnNew, twiSelf.Fn.Tree.btnEdit, twiSelf.Fn.Tree.btnDelete, twiSelf.Fn.Tree.btnRefresh);
            return items;
        }
    }//end ActionItems

    , Win: {
        createTreeWin: function () {
            var form = Ext.create('TAB.view.tree.TreeNewOrEditForm', { border: false });
            var win = Ext.create('Twi.QuickWin', {
                title: '窗口',
                width: 300,
                //x: 140,
                //y: 100,
                items: [form]
            });
            return { win: win,
                form: form
            }
        } //end createTreeWin
    } //end Win

    , Fn: {
        Tree:
        {
            newOrEditCommit: function (win, newOrEdit) {
                var form = win.form.form;
                var btnCommit = win.win.down('#btnSave');
                btnCommit.clearListeners();
                btnCommit.on('click', function () {
                    if (form.isValid()) {
                        btnCommit.disable();
                        var record = form.getValues();
                        var lenType = twiVars.treePanel.selModel.selected.length;
                        var data = {
                            TableName: twiVars.treeMappingName,
                            NewOrEdit: newOrEdit,
                            Fields: record,
                            SortModel: {
                                SortField: 'FSort',
                                FilterField: 'FParentID'
                            }
                        };
                        if ("Edit" == newOrEdit) {
                            data.Condition =
                            {
                                FID: record.FID
                            }
                            delete data.Fields.FID;
                        }
                        else {
                            var parentNode = twiVars.treePanel.selModel.selected.items[lenType - 1];
                            data.Fields.FVALUE = parentNode.data.dict.FVALUE;
                            data.Fields.FLEVEL = parseInt(parentNode.data.dict.FLEVEL) + 1;
                            data.Fields.FCODE = parentNode.data.dict.FCODE;
                        }
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'NewOrEdit',
                                data: Ext.encode(data)
                            },
                            success: function (obj) {
                                twiSelf.Fn.Tree.btnRefresh();
                                win.win.close();
                            }
                        });
                    }
                });
            } //end newOrEditCommit

            , btnNew: function () {
                var lenType = twiVars.treePanel.selModel.selected.length;
                if (lenType > 0) {
                    var win = twiSelf.Win.createTreeWin();
                    win.win.setTitle('新增树节点');
                    var record = twiVars.treePanel.selModel.selected.items[lenType - 1];
                    win.form.form.findField("FPARENTID").setValue(record.data.id);
                    win.form.form.findField("ParentName").setValue(record.data.text);
                    twiSelf.Fn.Tree.newOrEditCommit(win, 'New');
                    win.win.show();
                }
                else {
                    Twi.Msg.Info('', "请从选择父节点");
                }
            } //end btnNew

            , btnEdit: function () {
                var lenType = twiVars.treePanel.selModel.selected.length;
                if (lenType > 0) {
                    var win = twiSelf.Win.createTreeWin();
                    win.win.setTitle('编辑树节点');
                    var record = twiVars.treePanel.selModel.selected.items[lenType - 1];
                    if (record.data.level == "0") {
                        Twi.Msg.Error('', '该节点不能被编辑');
                        return;
                    }
                    var parentNode = twiVars.treePanel.store.getNodeById(record.data.parentId);
                    win.form.form.findField('FID').setValue(record.data.id);
                    win.form.form.findField("FPARENTID").setValue(parentNode.data.id);
                    win.form.form.findField("ParentName").setValue(parentNode.data.text);
                    win.form.form.findField("FNAME").setValue(record.data.text);
                    win.form.form.findField('FSORT').setValue(record.data.dict.FSORT);
                    win.form.form.findField('FREMARK').setValue(record.data.dict.FREMARK);
                    twiSelf.Fn.Tree.newOrEditCommit(win, 'Edit');
                    win.win.show();
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行编辑');
                }

            } //end btnEdit

            , btnDelete: function () {
                var len = twiVars.treePanel.selModel.selected.length;
                if (len > 0) {
                    var record = twiVars.treePanel.selModel.selected.items[len - 1];
                    if (record.data.level == "0") {
                        Twi.Msg.Error('', '该节点不能被删除');
                        return;
                    }
                    if (!record.data.leaf) {
                        Twi.Msg.Error('', '存在子节点时不能删除');
                        return;
                    }
                    
                    Twi.Msg.Confirm(function () {
                        var IDs = [];
                        Ext.each(twiVars.treePanel.selModel.selected.items, function (item, index, allItems) {
                            IDs.push(item.data.id);
                        });                        
                        var data = {
                            TableName: twiVars.treeMappingName,
                            IDs: IDs.join(',')
                        };
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'DeleteBySetFlag',
                                tableName: twiVars.treeMappingName,
                                data: Ext.encode(data)
                            },
                            success: function () {
                                //twiVars.treePanel.store.load();
                                twiSelf.Fn.Tree.btnRefresh();
                            }
                        });
                    },'警告','树结构为系统基础数据，在不是特别清楚系统逻辑的情况下，</br>不要轻易执行删除操作，否则容易引起系统错误！</br>删除后数据将不能恢复，是否继续执行？');

                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行删除');
                }
            } //end btnDelete

             , btnRefresh: function () {
                 //twiVars.treePanel.store.load();
                 Twi.QuickAjax.Ajax({
                     params: {
                         cn: 'Tree',
                         mn: 'TAB',
                         mn2: 'GetTreeData',
                         value: twiVars.sltTreeMappingValue
                     },
                     success: function (twi) {
                         var tree = twiVars.treePanel;
                         tree.store.setRootNode(twi.data[0]);
                         //tree.expandAll();
                         tree.expandNode(tree.getRootNode());
                     }
                 });
             } //end btnRefresh

            , btnQuery: function () {

            } //end btnQuery
        } //end Tree

    } //end Fn

};                                 //end Twi.TAB.TreeManage

var twiSelf = Twi.TAB.TreeManage;
var twiVars = twiSelf.Vars;

